package com.iotechn.unimall.admin.api.coupon;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dobbinsoft.fw.core.exception.AdminServiceException;
import com.dobbinsoft.fw.core.exception.ServiceException;
import com.dobbinsoft.fw.support.model.Page;
import com.iotechn.unimall.data.domain.XHCouponDO;
import com.iotechn.unimall.data.enums.XHCouponType;
import com.iotechn.unimall.data.exception.ExceptionDefinition;
import com.iotechn.unimall.data.mapper.XHCouponMapper;
import com.iotechn.unimall.data.vo.XHCouponVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class AdminXHCouponServiceImpl extends ServiceImpl<XHCouponMapper, XHCouponDO> implements AdminXHCouponService {
    @Override
    public Page<XHCouponVO> page(BigDecimal amountStart, BigDecimal amountEnd, Long issuerId, String holder, Integer status, Integer page, Integer limit, Long adminId) throws ServiceException {
        QueryWrapper<XHCouponVO> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(amountStart) && ObjectUtil.isNotEmpty(amountEnd)) {
            wrapper.between("coupon.discount", amountStart, amountEnd);
        }
        if (ObjectUtil.isNotEmpty(issuerId)) {
            wrapper.eq("coupon.issuer_id", issuerId);
        }
        if (ObjectUtil.isNotEmpty(holder)) {
            wrapper.like("`user`.nickname", holder);
        }
        if (ObjectUtil.isNotEmpty(status)) {
            wrapper.eq("coupon.`status`", status);
        }
        wrapper.orderByAsc("coupon.`status`");
        wrapper.orderByDesc("coupon.gmt_create");
        return baseMapper.pageXHCoupon(Page.div(page, limit, XHCouponVO.class), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(Long id, BigDecimal discount, Long adminId) throws ServiceException {
        XHCouponDO xhCouponDO = new XHCouponDO();
        xhCouponDO.setId(id);
        xhCouponDO.setDiscount(discount);
        if (baseMapper.updateById(xhCouponDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long id, Long adminId) throws ServiceException {
        if (baseMapper.deleteById(id) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchDelete(String ids, Long adminId) throws ServiceException {
        List<Long> idList = JSONObject.parseArray(ids, Long.class);
        if (baseMapper.deleteBatchIds(idList) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String grant(BigDecimal amount, String clientIds, String startTime, String entTime, Long adminId) throws ServiceException {
        List<Long> ids = JSONObject.parseArray(clientIds, Long.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<XHCouponDO> xhCouponDOS = new ArrayList<>();
        ids.forEach(id -> {
            try {
                XHCouponDO xhCouponDO = new XHCouponDO();
                xhCouponDO.setStatus(XHCouponType.STATUS_UNUSED.getCode());
                xhCouponDO.setUuid(UUID.randomUUID().toString().replace("-", "").substring(0,18));
                xhCouponDO.setDiscount(amount);
                xhCouponDO.setStartTime(sdf.parse(startTime));
                xhCouponDO.setEndTime(sdf.parse(entTime));
                xhCouponDO.setClientId(id);
                xhCouponDO.setGmtCreate(new Date());
                xhCouponDO.setIssuerId(adminId);
                xhCouponDOS.add(xhCouponDO);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        if (baseMapper.insertBatch(xhCouponDOS) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        return "ok";
    }

    @Override
    public String cancelAfterVerification(String uuid, Long adminId) throws ServiceException {
        QueryWrapper<XHCouponDO> couponWrapper = new QueryWrapper<>();
        couponWrapper.lambda().eq(XHCouponDO::getUuid,uuid);
        XHCouponDO xhCouponDO = baseMapper.selectOne(couponWrapper);
        if(ObjectUtil.isEmpty(xhCouponDO)){
            throw new AdminServiceException(ExceptionDefinition.COUPON_CODE_NOT_EXIST);
        }
        if (baseMapper.updateStatus(uuid) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        return "ok";
    }
}
